<template>
  <div class="flex justify-end mb-4">
    <EditSaveButton :isEdit="isEdit" @buttonClick="handleEdit" />
  </div>
  <div class="form-container">
    <el-form
      ref="designerFormRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      :disabled="disabled"
    >
      <el-form-item label="从业年限" prop="workExperience">
        <el-input v-model="formData.workExperience" placeholder="请输入从业年限">
          <template #append>年</template>
        </el-input>
      </el-form-item>
      <el-form-item label="简介" prop="introduce">
        <el-input v-model="formData.introduce" type="textarea" placeholder="请输入简介"></el-input>
      </el-form-item>
      <el-form-item label="服务区域" prop="serviceArea">
        <AreaSelector
          v-model="formData.serviceArea"
          :select-area-text="selectAreaText"
          class="w-full area-select"
        />
      </el-form-item>
      <el-form-item label="设计报价" prop="priceRange">
        <el-select v-model="formData.priceRange" placeholder="请选择报价" size="large">
          <el-option
            v-for="item in priceRangeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-for="item in props.dictCodes"
        :key="item.id"
        :label="item.name"
        :prop="item.fieldName"
      >
        <TagSelect
          :key="item.id"
          v-model="formData[item.fieldName]"
          :tag-list="item.dictDataList"
          :disabled="disabled"
        />
      </el-form-item>

      <el-form-item label="主页宣传" prop="indexImage">
        <MultiImageUpload v-model="formData.indexImage" :limit="10" :disabled="disabled" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { getEmployeeIndex, editEmployeeIndex } from "@/api/myIndex/index";
import TagSelect from "@/components/TagSelect/index.vue";
import AreaSelector from "@/components/AreaSelector/index.vue";
import DictDataAPI from "@/api/system/dict-data";
import { useDictStore } from "@/store/modules/dict";
import EditSaveButton from "../components/edit-save-button.vue";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();
const userId = computed(() => userStore.userInfo.userId);
const props = defineProps({
  dictCodes: {
    type: Array,
    default: () => [],
  },
});
const selectAreaText = ref("天津、北京、广东");
const formData = ref({
  workExperience: "", // 从业年限
  introduce: "", // 简介
  priceRange: [], // 设计报价
  indexImage: [], // 主页宣传
});
const dictStore = useDictStore();
const priceRangeList = ref([]);
const rules = ref({
  workExperience: [{ required: true, message: "请输入从业年限", trigger: "blur" }],
  introduce: [{ required: true, message: "请输入简介", trigger: "blur" }],
  serviceArea: [{ required: true, message: "请选择服务区域", trigger: "change" }],
  priceRange: [{ required: true, message: "请选择设计报价", trigger: "change" }],
  indexImage: [{ required: true, message: "请上传主页图片", trigger: "change" }],
});
const designerFormRef = ref(null);
const submitForm = async () => {
  let serviceArea = formData.value.serviceArea;
  try {
    return new Promise((resolve, reject) => {
      designerFormRef.value.validate(async (valid) => {
        if (valid) {
          let serviceAreas = "";
          if (serviceAreas) {
            serviceAreas = serviceArea.join(",");
          }
          let params = {
            merchantUserId: userId.value,
            ...formData.value,
            indexImage: JSON.stringify(formData.value.indexImage),
            serviceArea: serviceAreas,
          };

          props.dictCodes.forEach((item) => {
            console.log(item.fieldName, "item.fieldName");
            if (formData.value?.[item.fieldName]) {
              params[item.fieldName] = formData.value?.[item.fieldName]?.join(",");
            }
            console.log(params, "params");
          });
          if (defaultId.value) {
            params.id = defaultId.value;
          }
          try {
            await editEmployeeIndex(params);
            ElMessage.success(`${defaultId.value ? "更新" : "保存"}成功`);
            getDefaultMessage();
            isEdit.value = false;
            resolve(true);
          } catch (error) {
            console.error("保存失败", error);
            reject(false);
          }
          // 这里可以调用接口提交表单数据
        } else {
          console.error("表单验证失败");
          reject(false);
        }
      });
    });
  } catch (error) {
    console.error("保存失败", error);
    return false;
  }
};

const resetForm = () => {
  designerFormRef.value.resetFields();
};
// 是否编辑
const isEdit = ref(false);
const disabled = computed(() => !isEdit.value);
const handleEdit = () => {
  if (isEdit.value) {
    submitForm();
  } else {
    isEdit.value = !isEdit.value;
  }
};
/**
 * 获取默认表单数据
 */
const getDefaultMessage = async () => {
  try {
    const res = await getEmployeeIndex(userId.value);
    const data = res.data;
    if (!data) {
      isEdit.value = true;
      return;
    }
    //formData.value = data;
    formData.value = {
      workExperience: data.workExperience, // 从业年限
      introduce: data.introduce, // 简介
      priceRange: data.priceRange, // 设计报价
      indexImage: JSON.parse(data.indexImage), // 主页宣传
    };
    formData.value.serviceArea = data.serviceArea.split(",");
    props.dictCodes.forEach((item) => {
      formData.value[item.fieldName] = data[item.fieldName].split(",");
    });
    if (data?.id) {
      defaultId.value = data.id;
    }
    console.log(data, "formData.value");
  } catch (error) {
    console.error("获取默认消息失败", error);
  }
};
const handleDymaticRules = () => {
  // 动态生成规则
  let dymaticRules = props.dictCodes.map((item) => {
    return {
      [item.fieldName]: [{ required: true, message: `请选择${item.name}`, trigger: "change" }],
    };
  });

  rules.value = {
    workExperience: [{ required: true, message: "请输入从业年限", trigger: "blur" }],
    introduce: [{ required: true, message: "请输入简介", trigger: "blur" }],
    priceRange: [{ required: true, message: "请选择设计报价", trigger: "change" }],
    indexImage: [{ required: true, message: "请上传主页图片", trigger: "change" }],
    // ...dymaticRules,
  };
  for (let i = 0; i < dymaticRules.length; i++) {
    Object.assign(rules.value, dymaticRules[i]);
  }
  console.log(rules.value);
};
/**
 * 设计费价格
 */
const getPriceDicList = async () => {
  try {
    const data = await DictDataAPI.getPage({
      dictCode: "DesignFeePrice",
      pageNum: 1,
      pageSize: 1000,
    });
    dictStore.setDictionary({
      dictCode: "DesignFeePrice",
      dictDataList: data.list,
    });
  } catch (error) {
    console.error("获取价格字典列表失败", error);
  }
};
defineExpose({
  submitForm,
  resetForm,
  getDefaultMessage,
});
watch(
  props.dictCodes,
  (newVal) => {
    // 如果props.dictCodes有值，则动态生成表单规则
    if (newVal.length > 0) {
      handleDymaticRules();
      // 获取默认表单
    }
  },
  {
    immediate: true,
  }
);
let defaultId = ref("");
onMounted(async () => {
  getDefaultMessage();
  let priceRanges = dictStore.getDictionary("DesignFeePrice");
  if (priceRanges.length === 0) {
    await getPriceDicList();
  }
  priceRangeList.value = dictStore.getDictionary("DesignFeePrice");
});
</script>

<style scoped lang="scss">
/* 添加样式 */
.form-container {
  width: 70%;
  margin: 0 auto;
}
.area-select {
  :deep(.el-cascader) {
    width: 100%;
  }
}
</style>
